package com.dq.demos.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.dq.demos.web.pojo.ReqDataParamVo;
import com.dq.demos.web.pojo.ThirdUserBo;
import com.dq.demos.web.service.IYFKService;
import com.dq.demos.web.utils.BIPUtil;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.dq.demos.web.utils.ExceptionUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
/**
 * @Author: wxf
 * @Description: TODO 报销单保存
 * @Date: 2025/4/21 16:34
 * @Version: 1.0
 */
@RestController
@RequestMapping("/bxdToYFK")
public class ExpenseBillToFKController {
    private static Logger logger = LoggerFactory.getLogger(FPToYonFKController.class);
    public SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private IYFKService yfkService;
    @Autowired
    private ThirdUserBo thirdUserBo;

    /**
     * 付款单传友费控报销单保存接口
     * @param reqDataParamVo  请求参数
     * @return
     * @throws Exception
     */
    @RequestMapping("/saveBxd")
    public String saveBxd(@RequestBody ReqDataParamVo reqDataParamVo) throws  Exception{
//        String ksDate = reqDataParamVo.getBeginDate();
//        logger.info("----begin----> 调用友费控报销单保存后台任务开始，开始时间：【"+ymd.parse(ksDate)+"】");
        JSONObject requestParam = JSONObject.parseObject(reqDataParamVo.getJsonObject());
        //附件文件
        JSONArray filesBase64 = reqDataParamVo.getFilesBase64();
        //billno
        String billno = reqDataParamVo.getBillno();
        //手机号
        String searchCode = reqDataParamVo.getSearchCode();

        String isUploadFile = reqDataParamVo.getIsUploadFile();

        JSONObject return_data = new JSONObject();
        try{
            //1.获取友费控token
            String toKenURL = thirdUserBo.getBaseURL()+thirdUserBo.getSuffixTokenURL();
            String token = yfkService.getToken(toKenURL, thirdUserBo.getAppKey(), thirdUserBo.getAppSecret());
            logger.info("---->获取费控token; accessToken = " + token);
            HashMap<String, String> acctokenmap = new HashMap<>();
            acctokenmap.put("access_token", token);
            //2.上传附件文件
            if(filesBase64!=null && isUploadFile.equals("N")){
                String uploadUrl = thirdUserBo.getBaseURL()+thirdUserBo.getSuffixUploadURL();
                for (int i = 0; i < filesBase64.size(); i++) {
                    JSONObject fj_body =new JSONObject();
                    fj_body.put("billType","znbzbx_expensebill");
                    fj_body.put("fileName",((LinkedHashMap)filesBase64.get(i)).get("filename"));
                    fj_body.put("file",((LinkedHashMap)filesBase64.get(i)).get("file"));
                    fj_body.put("attachmentAss",billno);
                    String res = BIPUtil.getPostQueryParamAndBodyParam(uploadUrl, acctokenmap, fj_body);
                    JSONObject resp = JSONObject.parseObject(res);
                    if("200".equals(resp.getString("code"))){
                        logger.info("---->报销单保存接口账单上传附件文件请求参数: " + fj_body);
                        logger.info("---->报销单保存接口账单上传附件文件响应参数: " + res);
                    }else{
                        //错误码
                        return_data.put("code","001");
                        logger.error("---->报销单保存友费控异常:上传附件文件"+fj_body+"异常信息 " + resp);
                        throw new Exception("---->报销单保存友费控异常:上传附件文件"+fj_body+"异常信息 " + resp);
                    }
                }
            }
            //data赋值
            ((JSONObject) requestParam.get("data")).put("vattachmentass",billno);
            //3.查询账单列表
            JSONObject zd_body =new JSONObject();
            zd_body.put("pageIndex","1");
            zd_body.put("pageSize","10");
            JSONArray fplist =new JSONArray();
            JSONArray jsonArray = ((JSONObject)requestParam.get("data")).getJSONArray("expinvoicedetails");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = (JSONObject)jsonArray.get(i);
                fplist.add(object.get("vinvoiceno"));
            }
            zd_body.put("vinvoiceno",fplist);
            String zdUrl = thirdUserBo.getBaseURL()+thirdUserBo.getSuffixZDCXURL();
            String zdres = BIPUtil.getPostQueryParamAndBodyParam(zdUrl, acctokenmap, zd_body);
            JSONObject zdfresp = JSONObject.parseObject(zdres);
            if("200".equals(zdfresp.getString("code"))){
                logger.info("---->报销单保存接口账单列表请求参数: " + zd_body);
                logger.info("---->报销单保存接口账单列表响应: " + zdfresp);
            }else{
                logger.error("---->报销单保存友费控异常:查询账单列表"+zd_body+"异常信息 " + zdfresp);
                throw new Exception("---->报销单保存友费控异常:查询账单列表"+zd_body+"异常信息 " + zdfresp);
            }
            //后续操作  账单关联
            JSONArray jsonArray1 = ((JSONObject) zdfresp.get("data")).getJSONArray("recordList");
            if(jsonArray1==null || jsonArray1.size() != jsonArray.size()){
                logger.error("---->报销单保存友费控异常:查询不到子表对应发票号账单！！！");
                throw new Exception("---->报销单保存友费控异常:查询不到子表对应发票号账单！！！");
            }
            for (int i = 0; i < jsonArray1.size(); i++) {
                JSONObject object1=(JSONObject)jsonArray1.get(i);
                ((JSONObject)jsonArray.get(i)).put("pk_tallydata",object1.get("id").toString());
            }
            //4.获取租户账户  根据手机号
            String searchUrl = thirdUserBo.getBaseURL()+thirdUserBo.getSuffixSearchURL();
            JSONObject obj=new JSONObject();
            obj.put("searchcode",searchCode);
            String searchres = BIPUtil.getPostQueryParamAndBodyParam(searchUrl, acctokenmap, obj);
            JSONObject searchresp = JSONObject.parseObject(searchres);
            String result=new String();
            if("200".equals(searchresp.getString("code"))){
                logger.info("---->报销单保存接口账单获取租户账号请求参数: " + obj);
                logger.info("---->报销单保存接口账单获取租户账号响应参数: " + searchresp);
            }else{
                logger.error("---->报销单保存友费控异常:获取租户账户"+requestParam+"异常信息 " + searchresp);
                throw new Exception("---->报销单保存友费控异常:获取租户账户异常信息 " + searchresp);
            }
            JSONArray resultobj = (JSONArray)searchresp.getJSONObject("data").getJSONArray("content");
            if( resultobj!=null){
                JSONObject object =(JSONObject) resultobj.get(0);
                if(object.get("userCode")!=null){
                    result=object.get("userCode").toString();
                }
            }
            if(result==null){
                logger.error("---->报销单保存友费控异常:查询不到友费控租户账户，请检查65系统用户手机号与费控系统是否一致！！");
                //错误码
                throw new Exception("---->报销单保存友费控异常:查询不到友费控租户账户，请检查65系统用户手机号与费控系统是否一致！！");
            }
            //data赋值
            ((JSONObject) requestParam.get("data")).put("creator_code",result);
            //调用报销单保存
            String saveUrl = thirdUserBo.getBaseURL()+thirdUserBo.getSuffixBXDSaveURL();
            String res = BIPUtil.getPostQueryParamAndBodyParam(saveUrl, acctokenmap, requestParam);
            JSONObject resp = JSONObject.parseObject(res);
            JSONObject jsonObject = resp.getJSONObject("data");

            if("200".equals(resp.getString("code"))){
                logger.info("---->报销单保存请求参数: " + requestParam);
                logger.info("---->报销单保存接口响应: " + res);
            }else{
                logger.error("---->报销单保存友费控异常:报销单"+requestParam+"异常信息 " + resp);
                throw new Exception("---->报销单保存友费控异常:报销单保存异常信息 " + resp);
            }
            if(jsonObject.get("id")!=null)
            return_data.put("id",jsonObject.get("id"));
            else throw new Exception("---->报销单保存友费控异常:找不到报销单id！！");
            Thread.sleep(1000);
            logger.info("---->报销单保存成功");
        }catch (Exception e){
            logger.error("--->费控报销单保存异常：异常信息【"+e.getMessage()+"】");
            return ExceptionUtil.exceptionToJSON(return_data,"--->费控报销单保存异常：异常信息【"+e.getMessage()+"】","00");
        }
        logger.info("----end----> 调用友费控报销单保存结束");
        return ExceptionUtil.toJSON(return_data,"01","调用报销单保存成功，其他异常请查看跳板系统日志!日志路径【C:\\yonyou\\log】");
    }

}
